package web1.test;

import java.io.IOException;
import java.io.PrintStream;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Servletsql
 */
@WebServlet("/Servletsql")
public class Servletsql extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Servletsql() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("UTF-8");
    	PrintStream out = new PrintStream(response.getOutputStream());  
        response.setContentType("text/html;charSet=utf-8");  
        out.print("请正常打开此页");  
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		doGet(request, response);
		 StringBuffer json = new StringBuffer();  
	        json.append("[");  
	        try {  
	            database db = new database();  
	            ResultSet rs = db.query("select * from score");  
	            while (rs.next()) {  
	                json.append('{');  
	                //注意每一个key-value对都要在引号之中，单引号或者双引号都可以  

	                json.append("'id':").append("'").append(rs.getInt("id")).append("'").append(",");  
	                json.append("'name':").append("'").append(rs.getString("name").trim()).append("'").append(","); 
	                json.append("'score':").append("'").append(rs.getInt("score")).append("'").append(","); 

	                json.append("},");  
	            }   
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	        //这是为了删除最后一次循环中出现的那个逗号  

	        json.deleteCharAt(json.length() - 1);  
	        json.append("]");  
	        System.out.println(json);
	        PrintStream out = new PrintStream(response.getOutputStream());  
	        response.setContentType("text/html;charSet=utf-8");
	        //搞完把json打印在本Servlet上，之后前台页面读这页的内容就可以了  
	       /* response.getWriter().println(json.toString());
	        response.getWriter().flush();
	        response.getWriter().close();*/
	        out.println(json.toString());  
	        out.flush();
	        out.close();  
	}

}
